import 'package:inmotion_pro/config/r.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:inmotion_pro/pages/models/vehicle_error_model.dart';
import 'package:ble_helper_plugin/library.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:inmotion_pro/pages/others/common_enum/tbox_status_type.dart';
import 'package:inmotion_pro/service/cache_config_service.dart';
import 'package:lottie/lottie.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

// 车辆顶部信息视图
class VehicleTopInfoView extends StatelessWidget {
  // 车辆图片路径
  final String vehiclePath;

  // 剩余电量
  final double batteryLevel;

  // 剩余里程
  final double remainingMileage;

  // 警告消息列表
  final List<VehicleErrorModel> warningMsgList;

  // 蓝牙连接状态
  final CustomBluetoothConnectState bluetoothConnectState;

  // 云盒信号强度
  final int? tboxSignalLevel;

  // 是否车主
  final bool? isOwner;

  // 云盒在线/离线状态
  final TBoxStatus tboxStatusType;

  // 蓝牙点击
  final Function? bluetoothOnTap;

  // 锁车点击
  final Function? wifiOnTap;

  // 警告消息点击
  final Function? warningOnTap;

  const VehicleTopInfoView({
    super.key,
    required this.vehiclePath,
    required this.batteryLevel,
    required this.remainingMileage,
    required this.warningMsgList,
    required this.bluetoothConnectState,
    required this.tboxSignalLevel,
    required this.isOwner,
    required this.tboxStatusType,
    this.bluetoothOnTap,
    this.wifiOnTap,
    this.warningOnTap,
  });

  @override
  Widget build(BuildContext context) {
    // 中间图片的大小
    double imageSize = 180.w;
    return SingleChildScrollView(
      controller: ScrollController(),
      child: Column(
        children: [
          // 电量/剩余里程/4G/蓝牙
          _vehicleTopView(context),
          Center(
            child: Stack(
              alignment: Alignment.center,
              children: [
                Image.asset(
                  R.vehicleBackground,
                  width: screenWidth,
                  fit: BoxFit.fitWidth,
                ),

                // 车辆图片
                Image.asset(
                  vehiclePath,
                  height: imageSize,
                  fit: BoxFit.fitHeight,
                ),

                // 错误/警告
                _warningMsgView(context),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 电池电量/剩余里程/4G/蓝牙
  Widget _vehicleTopView(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: Padding(
        padding: EdgeInsets.only(
          left: CONTENT_MARGIN,
          right: CONTENT_MARGIN,
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 电量
                Row(
                  crossAxisAlignment: CrossAxisAlignment.baseline,
                  textBaseline: TextBaseline.ideographic,
                  children: [
                    LxText(
                      (batteryLevel * 100).round().toString(),
                      fontWeightEnum: LxFontWeightEnum.headlineMedium,
                    ),
                    const LxText(
                      " %",
                      fontWeightEnum: LxFontWeightEnum.bodyMedium,
                    ),
                  ],
                ),
                SizedBox(height: 4.w),
                // 电量进度条
                Container(
                  width: 100.w,
                  margin: EdgeInsets.only(top: 4.h),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(8.0),
                    child: LinearProgressIndicator(
                      minHeight: 5.w,
                      value: batteryLevel,
                      backgroundColor: Colors.grey,
                      color: BlueColor.blue7,
                    ),
                  ),
                ),
                SizedBox(height: 11.w),
                // 剩余里程
                Row(
                  crossAxisAlignment: CrossAxisAlignment.baseline,
                  textBaseline: TextBaseline.ideographic,
                  children: [
                    LxText(
                      context.s.remaining_mileage,
                      fontWeightEnum: LxFontWeightEnum.bodyMedium,
                      color: Colors.white.withOpacity(0.8),
                    ),
                    LxText(
                      " ${CacheConfigService.to.metricUnit(remainingMileage).$1.round().toString()}",
                      fontWeightEnum: LxFontWeightEnum.extraLarge,
                    ),
                    LxText(
                      " ${CacheConfigService.to.metricUnit(remainingMileage).$2}",
                      fontWeightEnum: LxFontWeightEnum.bodyExtraSmall,
                    ),
                  ],
                ),
              ],
            ),
            Padding(
              padding: EdgeInsets.only(top: 10.w),
              child: Row(
                children: [
                  // 信号图标
                  _signalImagePath == null
                      ? const SizedBox.shrink()
                      : RoundedInkWell(
                          onTap: () {
                            if (wifiOnTap != null) {
                              wifiOnTap!();
                            }
                          },
                          child: Image.asset(
                            _signalImagePath!,
                            width: 32.w,
                            fit: BoxFit.fitWidth,
                          ),
                        ),
                  SizedBox(width: 13.w),
                  // 蓝牙图标
                  RoundedInkWell(
                    onTap: () {
                      if (bluetoothOnTap != null) {
                        bluetoothOnTap!();
                      }
                    },
                    child: Visibility(
                      visible:
                          _toVehicleBleConnectState(bluetoothConnectState) ==
                              VehicleBleConnectState.connecting,
                      replacement: Image.asset(
                        _getBleStateAsset(bluetoothConnectState),
                        width: 32.w,
                        height: 32.w,
                        fit: BoxFit.fill,
                      ),
                      child: LottieBuilder.asset(
                        R.bleConnectingJson,
                        width: 32.w,
                        height: 32.w,
                        fit: BoxFit.fill,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 警告消息图标
  Widget _warningMsgView(BuildContext context) {
    return Visibility(
      visible: warningMsgList.isNotEmpty &&
          bluetoothConnectState == CustomBluetoothConnectState.connected,
      child: GestureDetector(
        onTap: () {
          if (warningOnTap != null) {
            warningOnTap!();
          }
        },
        child: Image.asset(
          R.vehicleErrorImage,
          width: 100.w,
          height: 100.w,
          fit: BoxFit.fitWidth,
        ),
      ),
    );
  }

  // 信号图标路径
  String? get _signalImagePath {
    if (isOwner == true) {
      switch (tboxStatusType) {
        case TBoxStatus.none:
          return null;
        case TBoxStatus.offline:
          return R.signal_4g_0;
        case TBoxStatus.online:
          // 只要蓝牙连接成功，才会显示信号强度，如果只是云盒在线但蓝牙未连接成功，则显示满格信号
          return bluetoothConnectState == CustomBluetoothConnectState.connected
              ? _build4GSignalIcon()
              : R.signal_4g_4;
      }
    }
    return null;
  }

  // 4G信号图标
  String _build4GSignalIcon() {
    String imgPath = R.signal_4g_0;
    switch (tboxSignalLevel) {
      case 0:
        imgPath = R.signal_4g_0;
        break;
      case 1:
        imgPath = R.signal_4g_1;
        break;
      case 2:
        imgPath = R.signal_4g_2;
        break;
      case 3:
        imgPath = R.signal_4g_3;
        break;
      case 4:
        imgPath = R.signal_4g_4;
        break;
      default:
        imgPath = R.signal_4g_4;
        break;
    }
    return imgPath;
  }

  // 映射蓝牙连接状态
  VehicleBleConnectState _toVehicleBleConnectState(
      CustomBluetoothConnectState state) {
    switch (state) {
      case CustomBluetoothConnectState.connected:
        return VehicleBleConnectState.connected;
      case CustomBluetoothConnectState.isScanning:
      case CustomBluetoothConnectState.connecting:
        return VehicleBleConnectState.connecting;
      default:
        return VehicleBleConnectState.disconnected;
    }
  }

  // 蓝牙连接状态对应的图片
  String _getBleStateAsset(CustomBluetoothConnectState state) {
    switch (state) {
      case CustomBluetoothConnectState.connected:
        return R.bleConnectedIcon;
      case CustomBluetoothConnectState.isScanning:
      case CustomBluetoothConnectState.connecting:
        return R.bleDisconnectedIcon;
      default:
        return R.bleDisconnectedIcon;
    }
  }
}
